import * as React from "react";
import { inject, observer } from "mobx-react";
import { Link } from 'react-router-dom';
import { Menu, Dropdown, Layout, Icon, Avatar, Badge } from 'antd';
import { HomeStore, } from '../../../store';
import { ClickParam } from "antd/lib/menu";
import { History } from 'history';
import ls from '../../../util/localStorage'
import * as signalR from "@aspnet/signalr";
import { CommonData } from '../../../basicData/data';
import { getByIdAsync } from '../../../basicData/api';
import { menus } from '../../../basicData/data';

import "../home.less";

const { Header } = Layout;
const { SubMenu } = Menu;

interface IProps {
  homeStore?: HomeStore;
  children?: AudioContextLatencyCategory;
  history: History;
}

interface State {
  isFullScreen: boolean,
}

const initialState: State = {
  isFullScreen: true,
};

type IState = Readonly<typeof initialState>;

@inject("homeStore")
@observer
class HomeHeader extends React.Component<IProps, IState> {
  readonly state: IState = initialState;

  componentDidMount() {
    const token = ls.get('token')

    if(token){

      const connection = new signalR.HubConnectionBuilder()
      .withUrl(`${CommonData.BaseWebSocket[process.env.NODE_ENV]}/notify`, {
        accessTokenFactory: () => `${token}`,
      } )
      .configureLogging(process.env.NODE_ENV === 'development' ? signalR.LogLevel.Information : signalR.LogLevel.None)
      .build();
  
      connection.start().catch((err: any) => console.log('err',err.toString()));
      
      connection.on('Connected', (message: any) => {
        // console.log('Connected',message)
      });
      connection.on('Sys.User.Active', (message: any) => {
        const data = JSON.parse(message)
        const obj = {
          messageId: data.MessageId,
          isChecked: false,
          type: 'newUser',
          content: JSON.parse(data.Content),
        }
        this.props.homeStore.getMessage(obj)
      });
      connection.on('Sys.User.ForgetPassword', (message: any) => {
        const data = JSON.parse(message)
        const obj = {
          messageId: data.MessageId,
          isChecked: false,
          type: 'forgerPwd',
          content: JSON.parse(data.Content),
        }
        this.props.homeStore.getMessage(obj)
      });
      connection.on('Sys.Announcement', (message: any) => {
        const data = JSON.parse(message)
        const obj = {
          messageId: data.MessageId,
          isChecked: false,
          type: 'announcement',
          content: JSON.parse(data.Content),
        }
        this.props.homeStore.getMessage(obj)
      });
      connection.on('Sys.Message.Clear', (message: any) => {
        const data = JSON.parse(message)
        let arr = [data.MessageId]
        this.props.homeStore.readMessage(arr)
      });
        
    }
  }

  toggle = () => {
    this.props.homeStore.changeCollapsed(!this.props.homeStore.collapsed);
  }

  selectMenu = (param: ClickParam) => {
    if (param.key === 'logout') {
      if(!ls.get('remember')) {
        ls.clear()
      } else{
        ls.remove(['token','effectiveTime','loginTime', ])
      }
      this.props.history.push('/login')
      let _window: any = window;
      _window.frames[0].postMessage('logout', `${CommonData.QRCodeURL[process.env.NODE_ENV]}/`);
    } else if(param.key === 'personalInfo') {
      this.props.history.push('/home/personalInfo')
    }
    else {
      // this.props.history.push('/home/changePwd')
      this.props.history.push('/home')
    }
  }
  messageList = () => {
    this.props.history.push('/home')
  }

  render() {
    const { userAuth, companyLogo, showEcode,userName } = this.props.homeStore
    const menu = (
      <Menu onClick={this.selectMenu}>
        <Menu.Item key="personalInfo"><Icon type="user" theme="outlined" />个人中心</Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout"><Icon type="logout" theme="outlined" />退出登录</Menu.Item>
      </Menu>
    );
    const tab = (
      <Menu className="home-header-logo-menu">
        <Menu.Item key="qrcode">
          <a href={`${CommonData.QRCodeURL[process.env.NODE_ENV]}/`}><Icon type="qrcode" /> 海普智联E码平台</a> 
        </Menu.Item>
      </Menu>
    );
    

    const headerMenu = () => {
      if(userAuth) {
        return menus(userAuth).map((menu) => (
            menu.show
            && <Menu.Item key={menu.key}>
              <span>{menu.title}</span>
              <Link to={menu.link} ></Link>
            </Menu.Item>
          ))
      }
    }

    return (
      <Header className="home-header" style={{ background: '#095092', padding: 0 }}>
        <div style={{fontSize: 18, display: 'flex'}}>
          
          {
            showEcode
            ? <Dropdown overlay={tab} placement="bottomCenter">
              <span className="home-header-logo">
                <Icon type="team" /> 
                <span> 海普权限平台 </span>
                <Icon type="down" />
              </span>
            </Dropdown>
            : <span className="home-header-logo">
              <Icon type="team" /> 
              <span> 海普权限平台 </span>
            </span>
          }
          <Menu
            mode="horizontal"
            selectedKeys={[this.props.homeStore.pathname]}
            className="home-header-menu"
          >
            {headerMenu()}
          </Menu>
        </div>
        <Dropdown overlay={menu} >
          <div className="user-info">
            <img src={companyLogo} alt=""/>
            {userName || ''}
          </div>
        </Dropdown>
      </Header>
    );
  }
}

export default HomeHeader